package com.aya.export.aspect;

import com.aya.export.annotation.ExcelExport;
import com.aya.export.core.Exporter;
import org.aopalliance.intercept.MethodInvocation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.AnnotationUtils;

import java.io.File;
import java.io.IOException;
import java.util.Collections;
import java.util.Map;
import java.util.Optional;

/**
 * @author ls9527
 * @date 2025/3/2
 */
public class ExcelExportService {
    @Autowired(required = false)
    private Map<String, Exporter> exporterMap;



    public Object processExport(MethodInvocation methodInvocation) throws IOException {
        ExcelExport excelExport = AnnotationUtils.getAnnotation(methodInvocation.getMethod(), ExcelExport.class);

        // 动态匹配Exporter或使用默认逻辑
        Exporter exporter = Optional.ofNullable(exporterMap)
                .map(Map::values)
                .orElse(Collections.emptyList())
                .stream()
                .filter(e -> e.getMode().equalsIgnoreCase(excelExport.mode()))
                .findFirst()
                .orElseThrow(() -> new IllegalStateException("No Exporter found for mode: " + excelExport.mode()));

        LocalStorageTempSave localStorageTempSave = new LocalStorageTempSave();
        localStorageTempSave.store(methodInvocation,  excelExport);

        final File localFile = localStorageTempSave.getLocalFile();
        final Object export = exporter.export(localFile);
        final boolean delete = localFile.delete();
        return export;
    }


}
